package com.laber.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.laber.domain.PageResult;
import com.laber.utils.ThreadLocalUtil;
import com.laber.domain.Article;
import com.laber.domain.PageResult;
import com.laber.mapper.ArticleMapper;
import com.laber.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);
    }

    @Override
    public PageResult<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //1.创建PageResult对象
        PageResult<Article> PageResult = new PageResult<>();

        //2.开启分页查询 PageHelper 相当于在之后执行两句sql
        // SELECT count(0) FROM xxx 和 在执行查询之后插入 limit (pageNum -1)*pageSize, pageSize
        // => (pageNum -1)*pageSize开始查询之后pageSize条数据
        PageHelper.startPage(pageNum, pageSize);

        //3.调用mapper
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

//        List<Article> articleList = articleMapper.list(userId, categoryId, state);
        //Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录条数和当前页数据
//        Page<Article> page = (Page<Article>) articleList;

        Page<Article> page = (Page<Article>) articleMapper.list(userId, categoryId, state);

        //把数据填充到PageResult对象中
        PageResult.setTotal(page.getTotal());
        PageResult.setItems(page.getResult());
        return PageResult;
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
